import Vue from 'vue';
import Vuex from 'vuex';
import { RouterTabRoutes } from 'vue-router-tab';
import emoji from 'utils/emoji';

Vue.use(Vuex);

/**
 * 路由生成器
 * @param {*} route
 */
const routeGenerator = (route) => {
  const BasicConfig = {
    path: route.path,
    name: route.name,
    meta: {
      title: route.title,
    },
  };

  return route.component
    ? {
        ...BasicConfig,
        component: () =>
          import(/* webpackChunName: "[request]" */ `../views${route.component}.vue`),
      }
    : BasicConfig;
};

export default new Vuex.Store({
  state: {
    menu: [],
    permission: [],
    asyncRoute: [],
    teachList: [],
    cateTree: [],
  },
  getters: {
    $menu: (state) => state.menu,
    $permission: (state) => state.permission,
    $asyncRoute: (state) => state.asyncRoute,
    $teacherList: (state) => state.teachList,
    $cateTree: (state) => state.cateTree,
  },
  mutations: {
    SET_MENUS(state, payload) {
      state.menu = payload;
    },
    SET_PERMISSION(state, payload) {
      state.permission = payload;
    },
    SET_ASYNCROUTE(state, payload) {
      state.asyncRoute = payload;
    },
    SET_TEACHERLIST(state, payload) {
      state.teachList = [...payload];
    },
    SET_CATETREE(state, payload) {
      state.cateTree = [...payload];
    },
  },
  actions: {
    $getTeacherList({ commit }, payload) {
      commit('SET_TEACHERLIST', payload);
    },

    $getCateTree({ commit }, payload) {
      commit('SET_CATETREE', payload);
    },

    $setMenus({ commit }, _) {
      // 过滤特殊标记的路由
      // const payload = _.filter((p) => !p.path.match(/^\/\$/));
      const payload = _;
      commit('SET_MENUS', _);

      // 构建路由
      let routes = [];

      payload.map((p) => {
        // 如果
        if (p.type === 1) {
          routes.concat(routeGenerator(p));
        }

        routes.push({
          ...routeGenerator(p),
        });

        if (Array.isArray(p.children)) {
          routes = routes.concat(
            p.children
              .filter((pChild) => pChild.type === 1)
              .map((pChild) => routeGenerator(pChild)),
          );
        }
      });

      commit('SET_ASYNCROUTE', [
        {
          path: '/d',
          component: () => import(/* webpackChunkName: "layout" */ '../layout/Dashboard.vue'),
          children: [
            {
              path: '',
              name: 'Welcome',
              meta: {
                title: 'Welcome',
              },
              component: () => import('../views/Welcome.vue'),
            },
            ...RouterTabRoutes,
            ...routes,
          ],
        },
      ]);
    },
    $setPermission({ commit }, payload) {
      commit('SET_PERMISSION', payload);
    },
  },
  modules: {},
});
